# -*- coding: utf-8 -*-
# Version: Python 3.9.7
# Author: TRIX
# Date: 2021-09-08 21:10:35
# Use: 暴力破解pdf密码 循环列举
import PyPDF3
from itertools import product


def decrypt_pdf(pdf_file, string):  # 目录 可能字符
    with open(pdf_file, 'rb') as f:
        reader = PyPDF3.PdfFileReader(f)  # 读取器
        with open(pdf_file[:-4] + '_decrypt.pdf', 'wb') as fd:
            writer = PyPDF3.PdfFileWriter()  # 写入器
            for n, ps_tuple in enumerate(product(string, repeat=len(string)), 1):
                password = ''.join(ps_tuple)
                reader.decrypt(password)  # 测试密码
                try:
                    for i in range(reader.numPages):
                        writer.addPage(reader.getPage(i))
                    writer.write(fd)
                    print('第{}次测试密码：{}  结果：成功'.format(n, password))
                    break
                except PyPDF3.utils.PdfReadError as e:
                    print('第{}次测试密码：{}  结果：失败'.format(n, password))
                    continue


decrypt_pdf(r'D:\_CodePrograms_\Python_Primary_Programs\document_processing\pdf_processing\decrypt_pdf\导学_tkvrO.pdf', 'kvtrO')
